package helper

import (
	"bytes"
	"context"
	"encoding/binary"
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/text/gregex"
	"net"
	"net/http"
	"strings"
	"time"
)

func Sleep(interval interface{}) {
	time.Sleep(time.Duration(interval.(int)) * time.Millisecond)
}

func PanicIgnore(ctx context.Context, try func(ctx context.Context), test func(err error)) {
	defer func() {
		if exception := recover(); exception != nil {
			if v, ok := exception.(error); ok {
				test(v)
			}
		}
	}()

	try(ctx)
}
func PanicIgnoreIndexDuplicate(ctx context.Context, try func(ctx context.Context)) {
	PanicIgnore(ctx, try, func(err error) {
		if gerror.Code(err) == gcode.CodeDbOperationError {
			matches, err := gregex.MatchString(`Error (\d+)`, err.Error())
			if err == nil {
				code := matches[1]
				if code != "1062" {
					panic(err)
				}
			}
		}
	})
}

func CookieRaw(cookieRaw string) []*http.Cookie {
	var cookies []*http.Cookie

	items := strings.Split(cookieRaw, "; ")
	for _, item := range items {
		keyValue := strings.Split(item, "=")
		name := keyValue[0]
		values := keyValue[1:]

		cookies = append(cookies, &http.Cookie{
			Name:  name,
			Value: strings.Join(values, "="),
		})
	}

	return cookies
}

func Ipv42Uint32(ipString string) uint32 {
	ip := net.ParseIP(ipString)
	if ip == nil {
		return 0
	}

	var ret uint32

	if err := binary.Read(bytes.NewBuffer(ip.To4()), binary.BigEndian, &ret); err != nil {
		return 0
	}

	return ret
}
func Uint322Ipv4(ipUint32 uint32) string {
	return fmt.Sprintf("%d.%d.%d.%d", byte(ipUint32>>24), byte(ipUint32>>16), byte(ipUint32>>8), byte(ipUint32))
}
